package com.infodms.dms.actions.sales.marketmanage.planissued;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.common.FileUploadManager;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.planissued.ActivitiesPlanIssuedDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesPlanManageDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanManageDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmDealerOrgRelationPO;
import com.infodms.dms.po.TtCamCampaignCostPO;
import com.infodms.dms.po.TtCamMediaCostPO;
import com.infodms.dms.po.TtCampaignExecuteChkPO;
import com.infodms.dms.po.TtCampaignExecutePO;
import com.infodms.dms.po.TtCampaignPO;
import com.infodms.dms.po.TtCampaignPoseChkRPO;
import com.infodms.dms.po.TtCampaignSpaceExecutePO;
import com.infodms.dms.po.TtVsCostPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * @Title: 活动执行方案审批Action
 * @Description:InfoFrame3.0.V01
 * @Copyright: Copyright (c) 2010
 * @Company: www.infoservice.com.cn
 * @Date: 2010-7-5
 * @author 
 * @mail  
 * @version 1.0
 * @remark 
 */
public class ActivitiesPlanAreaCheck {
	public Logger logger = Logger.getLogger(ActivitiesPlanAreaCheck.class);   
	ActivitiesPlanIssuedDao dao  = ActivitiesPlanIssuedDao.getInstance();
	ActivitiesPlanManageDao managedao  = ActivitiesPlanManageDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	private final String initUrl = "/jsp/sales/marketmanage/planissued/activitiesPlanAreaCheck.jsp";
	private final String detailUrl = "/jsp/sales/marketmanage/planissued/activitiesPlanAreaCheckDetail.jsp";
	/**
	 * 活动执行方案审批页面初始化
	 */
	public void activitiesPlanAreaCheckInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String orgId = logonUser.getOrgId().toString();
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			act.setOutData("orgId", orgId);
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动执行方案审批查询
	 */
	@SuppressWarnings("unchecked")
	public void activitiesPlanAreaCheckQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String orgId = logonUser.getOrgId().toString();
			Long poseId  = logonUser.getPoseId();
			String pOrgId = logonUser.getParentOrgId();
			//当没有上级组织时，将orgID置为-1
			if(pOrgId != null && "-1".equals(pOrgId)){
				orgId = "-1";
			}
			TtCampaignPoseChkRPO tcpcrp = new TtCampaignPoseChkRPO();
			tcpcrp.setPoseId(poseId);			
			List list = dao.select(tcpcrp);
			if(!CommonUtils.isNullList(list)){
				tcpcrp = (TtCampaignPoseChkRPO)dao.select(tcpcrp).get(0);
			}else {
				throw new RuntimeException("您没有审核权限，请联系系统管理员！");
			}
			
			String areaId=request.getParamValue("areaId");
			String queryStatus = tcpcrp.getQueryStatus().toString();
			String campaignNo = request.getParamValue("campaignNo");
			String campaignName = request.getParamValue("campaignName");
			String campaignSubject = request.getParamValue("campaignSubject");
			String dealerCode = request.getParamValue("dealerCode");
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate")) ;
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate")) ;
			
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.activitiesPlanAreaCheckQuery(startDate, endDate, poseId,areaId,campaignNo, campaignName, campaignSubject, dealerCode, orgId,queryStatus, curPage,Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		} catch (RuntimeException e) {
			logger.error(logonUser,e);
			act.setException(e);
		} catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,e.getMessage());
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动执行方案审批明细查询
	 */
	public void activitiesPlanAreaCheckDetail(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			/*
			 * 新增：
			 * 区域用户登陆时可看区域可用市场推广费用、经销商可用市场推广费用
			 * */
			String campaignId = request.getParamValue("campaignId");
			String executeId = request.getParamValue("executeId");
			String camType =request.getParamValue("camType") ;
			
			StringBuffer group_id = new StringBuffer();
			StringBuffer group_code = new StringBuffer();
			List<Map<String,String>> actList = managedao.queryActiveVehicleType(campaignId);
			if (null != actList && actList.size()>0) {
				for (int i = 0; i < actList.size(); i++) {
					group_id.append(String.valueOf(actList.get(i).get("GROUP_ID"))).append(",");
					group_code.append(String.valueOf(actList.get(i).get("GROUP_CODE"))).append(",");
				}
			}
			group_id.deleteCharAt(group_id.length()-1);
			group_code.deleteCharAt(group_code.length()-1);
			
			TtCampaignPO mypo1=new TtCampaignPO();
			mypo1.setCampaignId(Long.parseLong(campaignId));
			TtCampaignPO mypo2=new TtCampaignPO();
			mypo2=(TtCampaignPO) dao.select(mypo1).get(0);
			String areaId=String.valueOf(mypo2.getAreaId());
			
			Map<String, Object> map3 = dao.activitiesTargetQuery(executeId);
			List<Map<String, Object>> list3 = dao.getCheckInfo(executeId);
			List<Map<String, Object>> list4 = dao.getAttachInfo(campaignId);
			
			Map<String, Object> map2 = null ;
			List<Map<String, Object>> list1 = null ;
			List<Map<String, Object>> list2 = null ;
			
			if(!camType.equals(Constant.CAMPAIGN_TYPE_03.toString())) {
				map2 = dao.activitiesInfoQuery(campaignId, executeId,"111");
				String dealer_id = map2.get("DEALER_ID").toString();
				
				String area_org_id = logonUser.getOrgId().toString();
				
				String oem_org_id = logonUser.getCompanyId().toString();
				list1 = dao.getActivitiesCostbyId(executeId, campaignId,dealer_id,area_org_id,areaId,oem_org_id);
				list2 = dao.getActivitiesMediaCost(executeId,dealer_id,area_org_id,areaId,oem_org_id);
				
				
				List<Map<String, Object>> amountList1 = dao.queryDealerCost(dealer_id,areaId);
				List<Map<String, Object>> amountList2 = dao.queryAreaCost(dealer_id,areaId);
				
				if (amountList1.size() > 0) {
					act.setOutData("amountList1", amountList1.get(0).get(
							"AVAILABLE_AMOUNT"));
					System.out.println(amountList1.get(0).get("AVAILABLE_AMOUNT"));
				}
				if (amountList2.size() > 0) {
					act.setOutData("amountList2", amountList2.get(0).get(
							"AVAILABLE_AMOUNT"));
				}
			} else {
				TtCampaignSpaceExecutePO oldTcse = new TtCampaignSpaceExecutePO() ;
				oldTcse.setSpaceId(Long.parseLong(executeId)) ;
				TtCampaignSpaceExecutePO tcse = (TtCampaignSpaceExecutePO)dao.select(oldTcse).get(0) ;
				String areaOrgId = tcse.getOrgId().toString() ;
				map2 = dao.activitiesInfoQuery(campaignId, executeId, Long.parseLong(areaOrgId));
				
				List<Map<String, Object>> executePlans = SpacePlanManageDao.getInstance().getMyExecutePlanByCmpId(campaignId);
				
				list1 = ActivitiesPlanManageDao.getInstance().getActivitiesCostbyId(executeId, campaignId);
				list2 = SpacePlanReportDao.getActivitiesMediaCost(executeId);
				
				String amountList1 = "0" ;
				String amountList2 = SpacePlanReportDao.getCost(Long.parseLong(areaOrgId), areaId, Constant.COST_TYPE_02) ;
				
				act.setOutData("amountList1", amountList1);
				act.setOutData("amountList2", amountList2);
				act.setOutData("executePlans", executePlans) ;
			}
			
			
			
			
			
			
			Long orgId=logonUser.getOrgId();
			List<Map<String, Object>> amountList3 = dao.queryOemCost(orgId,areaId);
			
			if (amountList3.size() > 0) {
				act.setOutData("amountList3", amountList3.get(0).get(
						"AVAILABLE_AMOUNT"));
			}
						
						
						
						
						
			Map<String,Integer> mapA = new HashMap<String, Integer> () ;
			mapA.put("DEALER", Constant.COST_TYPE_01) ;
			mapA.put("AREA", Constant.COST_TYPE_02) ;
			mapA.put("OEM1", Constant.COST_TYPE_03) ;
			mapA.put("OEM2", Constant.COST_TYPE_04) ;
			
			Map<String,Integer> mapC = new HashMap<String, Integer> () ;
			mapC.put("cy03", Constant.CAMPAIGN_TYPE_03) ;
			
			String type = "" ;
			if(list1.size()>0&&list1.get(0).get("ITEM_COUNT")!=null){
				type = list1.get(0).get("COST_TYPE").toString() ;
			}
			if(list2.size()>0&&list2.get(0).get("ITEM_COUNT")!=null){
				type = list2.get(0).get("COST_TYPE").toString() ;
			}
			act.setOutData("type", type) ;
			
			act.setOutData("camType", camType) ;
			
			act.setOutData("mapA", mapA) ;
			act.setOutData("mapC", mapC) ;
			act.setOutData("list1", list1);
			act.setOutData("list2", list2);
			act.setOutData("list3", list3);
			act.setOutData("list4", list4);
			act.setOutData("map2", map2);
			act.setOutData("map3", map3);
			act.setOutData("group_id", group_id.toString());
			act.setOutData("group_code", group_code.toString());
			act.setForword(detailUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 活动执行方案审批提交
	 */
	public void activitiesPlanAreaCheckConfirm(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String areaId = request.getParamValue("areaId");
			String flag = request.getParamValue("flag");
			String isFleet = request.getParamValue("isFleetA") ;
			String camType = request.getParamValue("camType") ;
			
			ActivitiesCostOpera aco = new ActivitiesCostOpera() ;
			String costType = request.getParamValue("costType");
			aco.activeExecOpera(areaId, costType, flag, camType) ; 
			
			Long poseId  = logonUser.getPoseId();
			TtCampaignPoseChkRPO tcpcrp = new TtCampaignPoseChkRPO();
			tcpcrp.setPoseId(poseId);
			tcpcrp = (TtCampaignPoseChkRPO)dao.select(tcpcrp).get(0);
			Integer checkStatus = tcpcrp.getCheckStatus();
			Integer checkStatusA = tcpcrp.getQueryStatus() ;
			
			String executeId = request.getParamValue("executeId");
			String checkDesc = request.getParamValue("checkDesc");
			String []fjids = request.getParamValues("fjids");
			
			if (camType.equals(Constant.CAMPAIGN_TYPE_03.toString())) {
				String campaignId = request.getParamValue("campaignId") ;
				
				TtCampaignSpaceExecutePO tcse1 = new TtCampaignSpaceExecutePO() ;
				tcse1.setSpaceId(Long.parseLong(executeId)) ;
				
				TtCampaignSpaceExecutePO tcse2 = new TtCampaignSpaceExecutePO() ;
				
				if("0".equals(flag)){
					tcse2.setCheckStatus(checkStatus);
				}else{
					tcse2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_05);
				}
				
				tcse2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcse2.setUpdateBy(logonUser.getUserId());
				
				dao.update(tcse1, tcse2);
				
				TtCampaignExecuteChkPO tcecp = new TtCampaignExecuteChkPO() ;
				
				String checkId =SequenceManager.getSequence("");
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				tcecp.setCheckPositionId(logonUser.getPoseId());
				if("0".equals(flag)){
					tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_01);
				}else{
					tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_02);
				}
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//添加附件
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
				act.setOutData("returnValue", 1);
				
				TtCampaignExecutePO tcep1 = new TtCampaignExecutePO();
				tcep1.setCampaignId(Long.parseLong(campaignId)) ;
				
				TtCampaignExecutePO tcep2 = new TtCampaignExecutePO();
				
				if("0".equals(flag)){
					tcep2.setCheckStatus(checkStatus);
				}else{
					tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_05);
				}
				
				tcep2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcep2.setUpdateBy(logonUser.getUserId());
				
				Integer updateLen = dao.update(tcep1, tcep2);
				
				if(updateLen > 0) {
					List<Map<String, Object>> campaignList = dao.select(tcep1) ;
					
					TtCampaignExecutePO tce = null ;
					for(int i=0; i<updateLen; i++) {
						tce = (TtCampaignExecutePO)campaignList.get(i) ;
						executeId = tce.getExecuteId().toString() ;
						
						tcecp = new TtCampaignExecuteChkPO() ;
						
						checkId =SequenceManager.getSequence("");
						tcecp.setCheckId(Long.parseLong(checkId));
						tcecp.setExecuteId(Long.parseLong(executeId));
						tcecp.setCheckOrgId(logonUser.getOrgId());
						tcecp.setCheckDate(new Date(System.currentTimeMillis()));
						tcecp.setCheckDesc(checkDesc);
						tcecp.setCheckPositionId(logonUser.getPoseId());
						if("0".equals(flag)){
							tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_01);
						}else{
							tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_02);
						}
						tcecp.setCheckUserId(logonUser.getUserId());
						tcecp.setCreateBy(logonUser.getUserId());
						tcecp.setCreateDate(new Date(System.currentTimeMillis()));
						dao.insert(tcecp);
						
						//添加附件
						FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
						act.setOutData("returnValue", 1);
					}
				}
			} else {
				TtCampaignExecutePO tcep1 = new TtCampaignExecutePO();
				TtCampaignExecutePO tcep2 = new TtCampaignExecutePO();
				TtCampaignExecuteChkPO tcecp = new TtCampaignExecuteChkPO();
				tcep1.setExecuteId(Long.parseLong(executeId));
				
				if("0".equals(flag)){
					if("0".equals(isFleet) && checkStatusA.equals(Constant.CAMPAIGN_CHECK_STATUS_13)){	// 是大客户审核并且为大区最后一次审核
						tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_17);				// 改变审核状态为待大客户审核
					}else if(Constant.COST_TYPE_01.toString().equals(costType) && Constant.CAMPAIGN_CHECK_STATUS_15.equals(checkStatus)){	// 经销商费用并且是大区最后一次审核
						tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_06);	
					}else {
						tcep2.setCheckStatus(checkStatus);
					}
				}else{
					tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_05);
				}
				tcep2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcep2.setUpdateBy(logonUser.getUserId());
				dao.update(tcep1, tcep2);
				String checkId =SequenceManager.getSequence("");
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				if("0".equals(flag)){
					tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_01);
				}else{
					tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_02);
				}
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCheckPositionId(logonUser.getPoseId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//添加附件
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
			}
			act.setOutData("returnValue", 1);
		}catch(RuntimeException e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,e.getMessage());
			logger.error(logonUser,e1);
			act.setException(e);
		}
		catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批提交");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
}
